<?php

namespace app\admin\controller;

use app\common\lib\toCamelCase;
use app\common\model\mysql\SysRoleMenu;
use app\common\model\mysql\SysUserRole;
use think\facade\Db;

class Index extends AuthBase
{
    public function index(){
        $userId = $this->userId;
        $userInfo = $this->getUserInfo($userId);
        return show(config('status.success'),"登录失败",$userInfo);
    }

    public function getInfo(){
        $userId = $this->userId;
        $userInfo = $this->getUserInfo($userId);
        $this->getMenuIdArr($userInfo['userId']);
        $deptData = $this->getDeptInfo($userInfo['deptId']);
        $roleData = $this->getRoleInfo($userInfo['userId']);
        $roleKey = $this->getRoleKeyArr($userInfo['userId']);
        $array['user'] = $userInfo;
        $array['user']['params'] = array('@type'=>"java.util.HashMap");
        $array['user']['roles'] = $roleData;
        $array['user']['dept'] = $deptData;
        $array['user']['dept']['params'] = array('@type'=>"java.util.HashMap");
        $array['roles'] = $roleKey;
        $array['permissions'] = in_array('admin', $roleKey)?["*:*:*"]:$this->getMenuPermsArr($userInfo['userId']);
        return show(config('status.success'),"登录成功",$array);
    }

    public function getRoleIdsArr($userId){
        return (new SysUserRole())->getRoleIds($userId);
    }

    public function getRoleKeyArr($userId){
        $roleIds = $this->getRoleIdsArr($userId);
        $roleWhere = [
            ['role_id','in',$roleIds]
        ];
        return (new \app\common\business\SysRole())->getNormalRoleFiled($roleWhere,'role_key');
    }

    public function getMenuIdArr($userId){
        $roleIds = $this->getRoleIdsArr($userId);
        $menuIds = (new SysRoleMenu())->getRoleMenuInIdArray($roleIds);
        return array_values(array_unique($menuIds));
    }

    public function getMenuPermsArr($userId){
        $menuIds = $this->getMenuIdArr($userId);
        return (new \app\common\model\mysql\SysMenu())->getMenuInIdArray($menuIds);
    }

    public function getRoleInfo($userId){
        $roleIds = $this->getRoleIdsArr($userId);
        $roleWhere = [
            ['role_id','in',$roleIds]
        ];
        $roleData = (new \app\common\business\SysRole())->getNormalRoleNotPage($roleWhere);
        return (new toCamelCase)->toCamelCaseArray($roleData);
    }

    public function getDeptInfo($deptId){
        $deptWhere = [
            ['dept_id','=',$deptId]
        ];
        $deptData = (new \app\common\business\SysDept())->getNormalDept($deptWhere);
        return (new toCamelCase)->toCamelCaseArray($deptData);
    }

    public function getUserInfo($userId){
        // 如果直接使用Db类
        $userData = (new \app\common\model\mysql\SysUser())->getUserByIdArray($userId);
        return (new toCamelCase)->toCamelCaseArray($userData,2);
    }

    public function getRouters(){
        $userId = $this->userId;
        $roleKey = $this->getRoleKeyArr($userId);
        $menuIds = [];
        $where = [["status", "=", 0]];
        if (!in_array('admin', $roleKey)) {
            $menuIds = $this->getMenuIdArr($userId);
            $where[] = ["menu_id", "in", $menuIds];
        }
        $where[] = ["parent_id", "=", 0];
        $menuList = (new \app\common\business\SysMenu())->getNormalMenu($where, "*");
        $menuTree = $this->buildMenuTree($menuList, $userId, $roleKey, $menuIds);
        $menuTree = $this->menuListChildren($menuTree);
        return show(config('status.success'), "登录成功", $menuTree);
    }

    public function menuListChildren($menuList) {
        $result = [];
        foreach ($menuList as $menu) {
            $children = [];
            foreach ($menu['children'] as $child) {
                $processedChild = [
                    'component' => ($child['menu_type'] === "M" ? "ParentView" : $child['component']),
                    'hidden' => false,
                    'meta' => [
                        'icon' => $child['icon'],
                        'link' => $child['is_frame'] ? null : $child['path'],
                        'noCache' => false,
                        'title' => $child['menu_name'],
                    ],
                    'name' => ucfirst($child['path']),
                    'path' => $child['path'],
                ];
                if ($child['menu_type'] === "M") {
                    $childrens = [];
                    foreach ($child['children'] as $value) {
                        $processedChilds = [
                            'component' => $value['component'],
                            'hidden' => false,
                            'meta' => [
                                'icon' => $value['icon'],
                                'link' => $value['is_frame'] ? null : $value['path'],
                                'noCache' => false,
                                'title' => $value['menu_name'],
                            ],
                            'name' => ucfirst($value['path']),
                            'path' => $value['path'],
                        ];
                        $childrens[] = $processedChilds;
                    }
                    if (!empty($childrens)) {
                        $processedChild['children'] = $childrens;
                    }
                    if ($child['is_frame'] == 1) {
                        $processedChild['alwaysShow'] = true;
                        $processedChild['redirect'] = 'noRedirect';
                    }
                }
                $children[] = $processedChild;
            }
            $processedMenu = [
                'component' => "Layout",
                'hidden' => false,
                'meta' => [
                    'icon' => $menu['icon'],
                    'link' => $menu['is_frame'] ? null : $menu['path'],
                    'noCache' => false,
                    'title' => $menu['menu_name'],
                ],
                'name' => ucfirst($menu['path']),
                'path' => $menu['is_frame'] ? '/' . $menu['path'] : $menu['path'],
            ];
            if (!empty($children)) {
                $processedMenu['children'] = $children;
            }
            if ($menu['is_frame'] == 1) {
                $processedMenu['alwaysShow'] = true;
                $processedMenu['redirect'] = 'noRedirect';
            }
            $result[] = $processedMenu;
        }
        return $result;
    }

    public function buildMenuTree($menuList, $userId, $roleKey, $menuIds) {
        $result = [];
        $menuMap = []; // 使用哈希表来存储已经处理过的菜单项
        $SysMenuDb = (new \app\common\business\SysMenu());
        foreach ($menuList as $menu) {
            $menuId = $menu['menu_id'];
            if (isset($menuMap[$menuId])) {
                continue; // 避免重复处理相同的菜单项
            }
            $menuMap[$menuId] = true; // 标记为已处理
            if (!in_array('admin', $roleKey) && !in_array($menuId, $menuIds)) {
                continue; // 如果用户没有权限，跳过此菜单
            }
            $children = $this->getChildMenus($menuId, $roleKey, $menuIds,$SysMenuDb);
            $menu['children'] = $this->buildMenuTree($children, $userId, $roleKey, $menuIds); // 递归构建子菜单
            $result[] = $menu;
        }
        return $result;
    }

    public function getChildMenus($parentId, $roleKey, $menuIds,&$SysMenuDb) {
        $where = [
            ["parent_id", "=", $parentId],
            ["status", "=", 0],
            ["menu_type", "<>", "F"],
        ];
        return $SysMenuDb->getNormalMenu($where, "*");
    }
}
